package de.breitbeil.jbooking.ui.components;

import java.awt.Color;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;

import org.jdesktop.swingx.JXMonthView;

import de.breitbeil.jbooking.domain.Booking;

public class BookingCalendarComponent extends JXMonthView {

    private HashMap<Date, Booking> startingDates = new HashMap<Date, Booking>();
    private HashMap<Date, Booking> endingDates = new HashMap<Date, Booking>();
    private HashMap<Date, Booking> innerBookings = new HashMap<Date, Booking>();

    private HashSet<Booking> bookings = new HashSet<Booking>();
    
    private Color bookingColor = new Color(0xf69a9a);
    private Color reservationColor = new Color(0x9df69d);

    public void addBooking(Booking booking) {
        String bookingType = booking.getBookingType().getText();
        if("reservation".equals(bookingType) || "booking".equals(bookingType)) {
            bookings.add(booking);
        }
        rebuildDateSets();
        repaint();
    }
    
    public void removeBooking(Booking booking) {
        bookings.remove(booking);
        rebuildDateSets();
        repaint();
    }
    
    protected void rebuildDateSets() {
        for(Booking booking: bookings) {
            Date from = booking.getFrom();
            Date to = booking.getTo();
            
            startingDates.put(from, booking);
            endingDates.put(to, booking);
            
            Calendar toCalendar = Calendar.getInstance();
            toCalendar.setTime(to);
            Calendar cal = Calendar.getInstance();
            cal.setTime(from);
            cal.add(Calendar.DATE, 1);
            while(cal.before(toCalendar)) {
                innerBookings.put(cal.getTime(), booking);
                cal.add(Calendar.DATE, 1);
            }
        }
    }
    
    @Override
    public void updateUI() {
        setUI(new BookingCalendarUi());
        invalidate();
    }

    public Booking getBookingForStartDate(Date date) {
        return startingDates.get(date);
    }
    
    public Booking getBookingForEndDate(Date date) {
        return endingDates.get(date);
    }

    public Booking getBookingForInnerDate(Date date) {
        return innerBookings.get(date);
    }

    public Color getColorForBooking(Booking booking) {
        if(booking.getBookingType().getText().equals("booking")) {
            return bookingColor;
        }
        if(booking.getBookingType().getText().equals("reservation")) {
            return reservationColor;
        }
        
        return getBackground();
    }

}
